<template>
  <div>
    <myDivider :name="type == 'detail' ? '晨会详情' : '新增晨会'"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>
    <el-form style="width: 600px;margin-top: 50px;" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
      class="demo-ruleForm">
      <div style="display: flex;">
        <el-form-item label="会议时间：" prop="" required>
          <el-input style="width: 200px;" disabled v-model="ruleForm.meetingTime" placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="所属单位：" prop="" required>
          <el-input style="width: 200px;" disabled v-model="ruleForm.unitName"></el-input>
        </el-form-item>
        <el-form-item label="参与部门：" prop="deptId">
          <el-select v-if="type == 'add'" ref="dept" @change="deptChange" style="width: 200px;"
            :disabled="type == 'detail'" v-model="ruleForm.deptId" placeholder="请选择部门" clearable>
            <el-option v-for="item, i in deptData" :key="i" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-input v-else disabled v-model="ruleForm.deptName" placeholder="" style="width: 200px;"></el-input>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item v-if="type == 'detail'" label="会议编号：" prop="meetingNumber">
          <el-input disabled style="width: 200px;" v-model="ruleForm.meetingNumber" placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="参会人数：" prop="count">
          <el-input @input="ruleForm.count = ruleForm.count.replace(/\D/g, '');" :disabled="type == 'detail'"
            type="number" style="width: 170px;margin-right: 10px;" v-model="ruleForm.count" :maxlength="5"
            placeholder="请输入参会人数" oninput="if(value.length > 4) value=value.slice(0, 4)"></el-input>
          <span>人</span>
        </el-form-item>
      </div>
      <el-form-item label="会议概要：" prop="description">
        <el-input :disabled="type == 'detail'" style="width: 500px;" v-model="ruleForm.description" type="textarea"
          :rows="5" maxlength="800" show-word-limit placeholder="请输入会议概要，不超过800字"></el-input>
      </el-form-item>
      <el-form-item label="图片：" prop="" required>
        <myuploadByCHGLImg :id="uploadId" v-if="type == 'add' && imgAndFile" ref="byimg" @getImgList="getImgList"
          uploadUrl="/business/meeting/uploadImg"
          deleteUrl="/business/meeting/deleteImg"></myuploadByCHGLImg>
        <div class="imglist" v-else>
          <el-image class="el" style="width: 100px; height: 100px" v-for="item, i in ruleForm.imgs" :key="i" :src="item"
            :preview-src-list="ruleForm.imgs">
          </el-image>
        </div>
      </el-form-item>
      <el-form-item label="附件：">
        <myuploadByCHGLFile :id="uploadId" ref="byfile" v-if="type == 'add' && imgAndFile"
          uploadUrl="/business/meeting/uploadAnnex"
          deleteUrl="/business/meeting/deleteAnnex" @getFileList="getFileList">
        </myuploadByCHGLFile>
        <!-- <el-button v-else style="width: 200px;" type="primary" plain @click="dow(ruleForm.annexPathArr)">下载附件</el-button> -->
        <div class="annexBox" v-else>
          <div class="annexList" v-if="ruleForm.annexPathArr != null">
            <div class="el" v-for="item, i in MyannexPathArr" :key="i">
              <span>{{ item.name }}</span>
              <span @click="dow(item)">下载附件</span>
            </div>
          </div>
          <span class="annexNone" v-else>无添加附件</span>
        </div>
      </el-form-item>
      <el-form-item label="经办人：" prop="" required>
        <el-input disabled style="width: 200px;" v-model="ruleForm.userName" placeholder="自动匹配"></el-input>
      </el-form-item>
      <el-form-item label="详细位置：" prop="address" required>
        <el-input disabled style="width: 500px;" v-model="ruleForm.address" placeholder="请选择地图上的位置"></el-input>
      </el-form-item>
      <el-form-item class="btn" v-if="type == 'add'">
        <el-button style="width: 100px;" type="primary" @click="submitForm('ruleForm')">新增</el-button>
        <el-button style="width: 100px;" type="info" @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 地图 -->
    <div class="mapStyle">
      <div id="container">
      </div>
      <div class="keyAddressStyle">
        <el-input placeholder="省/市/区" v-model="keyAddress">
          <el-button slot="append" icon="el-icon-search" @click="addressChange"></el-button>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
window._AMapSecurityConfig = {
  securityJsCode: "74a9bc741a93c4984284167952f22f4a",//安全密钥
};
import 'default-passive-events'
import AMapLoader from '@amap/amap-jsapi-loader';
import myuploadByCHGLFile from '../../components/upload/myuploadByCHGLFile';
import myuploadByCHGLImg from '../../components/upload/myuploadByCHGLImg';
import axios from 'axios';
export default {
  components: {
    myuploadByCHGLFile,
    myuploadByCHGLImg
  },
  data() {
    return {
      imgAndFile: false,
      deptData: [],
      type: '',//新增还是详情
      keyAddress: '',
      ruleForm: {},
      rules: {
        deptId: [
          { required: true, message: '请选择参与部门', trigger: 'change' }
        ],
        count: [
          { required: true, message: '请填写参会人数', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请写入会议概要', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请填写经办人', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写详细位置', trigger: 'blur' }
        ],
      },
      map: null,//地图
      marker: null,//点标点
      geocoder: null,//编码
      MyannexPathArr: [],
      uploadId: 0,
    };
  },
  async activated() {
    this.uploadId = 0
    this.type = this.$route.query.type //新增？详情？
    this.getDept() //获取部门列表
    this.keyAddress = ''
    let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    if (this.type == 'add') {
      this.imgAndFile = false
      setTimeout(() => {
        this.imgAndFile = true
      }, 100)
      let nowTime = new Date()
      let year = nowTime.getFullYear()
      let month = nowTime.getMonth() + 1 < 10 ? '0' + (nowTime.getMonth() + 1) : nowTime.getMonth() + 1
      let day = nowTime.getDate() < 10 ? '0' + nowTime.getDate() : nowTime.getDate()
      this.$set(this.ruleForm, 'meetingTime', `${year}-${month}-${day}`) //会议时间回显

      this.$set(this.ruleForm, 'unitName', logOnUser.unitType == 'system' ? '系统' : logOnUser.unitName)
      this.$set(this.ruleForm, 'userName', logOnUser.name)
      this.$set(this.ruleForm, 'deptName', '')
      this.$set(this.ruleForm, 'deptId', '')
      this.$set(this.ruleForm, 'meetingNumber', '')
      this.$set(this.ruleForm, 'count', '')
      this.$set(this.ruleForm, 'description', '')
      this.$set(this.ruleForm, 'address', '')
      this.$set(this.ruleForm, 'imgs', [])
      this.$set(this.ruleForm, 'annexPathArr', [])
    }
    if (this.type == 'detail') {
      let id = this.$route.query.id
      let res = await this.$api.metting.getMeetingDetail(id)
      this.MyannexPathArr = []
      if (res.data.annexPathArr != null) { //附件列表回显
        res.data.annexPathArr.forEach((el) => {
          let lastindex = el.lastIndexOf("/") + 1
          this.MyannexPathArr.push({
            name: el.slice(lastindex),
            url: el
          })
        })
      }
      this.ruleForm = res.data
    }
    this.initAMap(); //初始化地图
    this.$nextTick(() => { //清除验证
      this.$refs['ruleForm'].clearValidate()
    })
  },
  methods: {
    deptChange(val) {
      this.$nextTick(() => {
        this.$set(this.ruleForm, 'deptName', this.$refs.dept.selectedLabel)
      })
    },
    async getDept() {
      let res = await this.$api.metting.getDept()
      if (res.code == 200) {
        this.deptData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    dow(item) { //下载附件

      let soa_account = sessionStorage.getItem("soa_account");
      const token = sessionStorage.getItem("soa_token")
      axios({
        method: 'get',
        url: defaultUrl+`/business/meeting/downloadAnnex?filename=${item.url}`,
        headers: {
          // 在这里添加自己需要的请求头
          account: soa_account,
          token: token,
        },
        responseType: 'blob'
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const a = document.createElement('a')
        a.href = url
        a.setAttribute('download', item.name)
        document.body.appendChild(a)
        a.click();
        document.body.removeChild(a)
      })
    },
    getFileList(files) { //附件列表
      this.$set(this.ruleForm, 'annexPathArr', files)
    },
    getImgList(imgs) { //图片列表
      this.$set(this.ruleForm, 'imgs', imgs)
    },
    // 输入关键字定位
    addressChange() {
      this.geocoder.getLocation(this.keyAddress, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          console.log(result.geocodes[0].location);
          let lng = result.geocodes[0].location.lng
          let lat = result.geocodes[0].location.lat
          this.map.setCenter([lng, lat], true)
          this.map.setZoom(14)
          console.log(this.marker, '芜湖');
          if (this.marker != null) {  //如果之前有点标点那去除
            this.marker.remove()
            this.marker = new AMap.Marker({ //创建点标点
              position: [lng, lat],
            });
            this.map.add(this.marker);
          } else {
            this.marker = new AMap.Marker({ //创建点标点
              position: [lng, lat],
            });
            this.map.add(this.marker);
          }

        }
      })
    },
    async DetailData() { //数据回显
      let res = await this.$api.metting.getMeetingDetail(this.$route.query.id)
      this.map.setCenter(res.data.locationArr, true)
      this.map.setZoom(14)
      this.marker = new AMap.Marker({ //创建点标点
        position: res.data.locationArr,
      });
      this.map.add(this.marker);
    },
    initAMap() {
      AMapLoader.load({
        resizeEnable: true,
        key: "b59ffa4664995330f554d4aedc02b03c",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D",
            zoom: 11,
            center: [116.206118, 39.990569],
          });
          this.map.on('complete', () => { //地图加载完毕函数
            this.geocoder = new AMap.Geocoder()
            switch (this.type) {
              case 'add':
                this.map.on("click", (ev) => { //地图点击增加点标，获取位置
                  if (this.marker != null) {  //如果之前有点标点那去除
                    this.marker.remove()
                  }
                  let { lng, lat } = ev.lnglat;   //获取到的经纬度
                  this.marker = new AMap.Marker({ //创建点标点
                    position: [lng, lat],
                  });
                  this.$set(this.ruleForm, 'locationArr', [lng, lat]) //新增表单需要经纬度字段
                  this.map.add(this.marker);    //添加点标点
                  this.geocoder.getAddress([lng, lat], (status, result) => { //获取点击的位置
                    console.log(status, result);
                    if (status === 'complete' && result.info === 'OK') {
                      this.$set(this.ruleForm, 'address', result.regeocode.formattedAddress)
                    }
                  })
                });
                break
              case 'detail':
                this.DetailData() //详细数据回显
                break
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    submitForm(formName) {
      if (this.type == 'detail') {
        return
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.ruleForm.annexPathArr == undefined) { //如果没选附件
            this.ruleForm.annexPathArr = []
          }
          if (this.ruleForm.imgs == undefined || this.ruleForm.imgs.length < 1) { //如果图片为空或者图片数量为0
            this.$message.error('请上传图片')
            return
          }
          this.$confirm('是否新增晨会记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let { deptId, deptName, count, description, imgs, annexPathArr, locationArr, address } = this.ruleForm
            let params = { deptId, deptName, count, description, imgs, annexPathArr, locationArr, address }
            let res = await this.$api.metting.insertMeeting(params)
            if (res.code == 200) {
              this.$message({
                message: '记录新增成功',
                type: 'success'
              });
              this.$router.back(-1)
            } else {
              this.$message.error(res.message)
            }
          }).catch(() => {

          });

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$router.back(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.annexBox {
  width: 500px;

  .annexList {
    width: 100%;
    box-sizing: border-box;
    border-right: 3px solid rgb(23, 197, 255);

    .el {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      span {
        &:nth-child(1) {
          width: 300px;
          display: block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        &:nth-child(2) {
          color: rgb(23, 197, 255);
          cursor: pointer;
          margin-right: 10px;
        }
      }
    }
  }

  .annexNone {
    color: #aaa;
  }
}

.btn {
  position: fixed;
  bottom: 10px;
  right: 40px;
}

.imglist {
  .el {
    border-radius: 5px;
    overflow: hidden;
    margin-right: 10px;
  }
}

.mapStyle {
  height: 400px;
  width: 900px;
  margin-left: 100px;
  position: relative;
  margin-bottom: 100px;

  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;

  }

  .keyAddressStyle {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 250px;
    height: 30px;
  }
}
</style>